package com.shopping.mall.core.module.paypal.config;


import com.alibaba.fastjson.JSONObject;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
import com.shopping.mall.base.http.httpclient.util.HttpUtils;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: 
 * @description:
 * @author: 
 * @create: 
 **/
@Configuration
public class PaypalConfig {

    @Value("${paypal.client.app}")
    private String clientId;
    @Value("${paypal.client.secret}")
    private String clientSecret;
    @Value("${paypal.mode}")
    private String mode;

    @Autowired
    private HttpUtils httpUtils;

    public Map<String, String> paypalSdkConfig(){
        Map<String, String> sdkConfig = new HashMap<>();
        sdkConfig.put("mode", mode);
        return sdkConfig;
    }

    public OAuthTokenCredential authTokenCredential(){
        return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig());
    }


    public APIContext apiContext() throws PayPalRESTException, UnsupportedEncodingException {
        String token=getToken();
        System.out.println("token在这里");
        System.out.println(token);
        System.out.println("Bearer "+token);
        System.out.println(authTokenCredential().getAccessToken());
        APIContext apiContext = new APIContext("Bearer "+token);
        apiContext.setConfigurationMap(paypalSdkConfig());

        return apiContext;
    }

    public String getToken() throws UnsupportedEncodingException {
        try {
            String url="https://api-m.paypal.com/v1/oauth2/token";
            String encoding = Base64.getUrlEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
            Map<String,String> headers=new HashMap<>();
            System.out.println(encoding);
            headers.put("Authorization","Basic "+encoding);
            Map<String,String> params=new HashMap<>();
            params.put("grant_type","client_credentials");
            JSONObject jsonObject=httpUtils.postForForm(url,params,encoding);
            return (String) jsonObject.get("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
//        System.out.println(result);
//        return null;
    }
}

